import { Button, Card, Col, Row, Typography, Image } from "antd"
import React, { useContext } from "react"
import { Link } from "react-router-dom"
import moment from "_moment@2.29.1@moment"
import { API } from "../config"
import { add2Cart, getItemCount } from "../hooks/cart"
import { CategoryItem } from "../hooks/categories"
import { CountContext } from "./context/cartItemCount"
const { Title, Paragraph } = Typography

export interface ProductItemFace {
    "sold": number,
    "_id": string,
    "name": string,
    "description": string,
    "price": number,
    "category": CategoryItem,
    "quantity": number,
    "shipping": boolean,
    "createdAt": string,
    "updatedAt": string,
    "__v": number,
    photo?: {
        contentType: string,
        data: any
    }
}
interface Props {
    product: ProductItemFace
    showViewProduct?: boolean
    showCartBtn?: boolean
}



const ProductItem = ({ product, showViewProduct = true, showCartBtn = true }: Props) => {
    const [count, setCount] = useContext(CountContext)

    const cardActionBtns = () => {
        let arr: JSX.Element[] = []
        if (showViewProduct) {
            arr.push(
                <Button type="link">
                    <Link to={`/product/${product._id}`}>查看详情</Link>
                </Button>
            )
        }
        if (showCartBtn) {
            arr.push(
                <Button type="link" onClick={() => {
                    add2Cart(product)
                    setCount(getItemCount())
                }}>加入购物车</Button>
            )
        }

        return arr
    }

    return (
        <>
            <Card
                cover={
                    <Image src={API + `/product/photo/${product._id}`} alt={product.name} />
                }
                actions={cardActionBtns()}>
                <Title level={5}>{product.name}</Title>
                <Paragraph ellipsis={{ rows: 2 }}>描述：{product.description}</Paragraph>
                <Row>
                    <Col span="12">销量：{product.sold}</Col>
                    <Col span="12" style={{ textAlign: 'right' }}>价格：{product.price}</Col>
                </Row>
                <Row>
                    <Col span="12">上架时间：{moment(product.createdAt).format('YYY-MM-DD')}</Col>
                    <Col span="12" style={{ textAlign: 'right' }}>所属分类：{product.category.name}</Col>
                </Row>
            </Card>
        </>
    )
}

export default ProductItem
